package cn.yunhe.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class SqlSessionFactoryUtil {
    //编写工具类获取SqlSession对象

    private static SqlSessionFactory factory;
    private  SqlSessionFactoryUtil(){}
    static {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis.xml");  //读取配置文件信息
            factory = new SqlSessionFactoryBuilder().build(reader); //通过读取到的配置信息获取factory对象
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader!=null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static SqlSession getSqlSession(){
        return factory.openSession();
    }
}
